<template>
  <div ref="messureChartRef" class="flex items-center justify-center">
    暂无数据
  </div>
</template>

<script setup lang="tsx">
import { nextTick, useTemplateRef, watch } from 'vue';
import * as eCharts from 'echarts';

const messureChartRef = useTemplateRef('messureChartRef');

const props = defineProps({
  dataList: {
    type: Array,
    default: () => [],
  },
  grid: {
    type: Object,
    default: () => ({
      top: '20%',
      bottom: '14%', // 调整底部留白，单位是像素
      left: '10%',
      right: '0%',
    }),
  },
});

const colorEnum = {
  0: '#F4A966',
  1: '#38C3FF',
};

const nameEnum = {
  0: '自由场',
  1: '结构场',
};

const renderChart = () => {
  if (!props.dataList.length) return;

  const _data = [];
  const freeList = [];
  const structureList = [];
  const _xAxis = [];
  props.dataList?.map((item: any) => {
    _xAxis.push(item.date);
    freeList.push(item.free);
    structureList.push(item.structure);
  });
  [0, 1].forEach((item, idx) => {
    _data.push({
      name: nameEnum[idx],
      type: 'bar',
      barWidth: '10',
      itemStyle: {
        color: colorEnum[idx], // 设置柱状图和图例的颜色为红色
      },
      data: item === 0 ? freeList : structureList,
    });
  });

  const option = {
    tooltip: {
      trigger: 'axis', // 悬浮在 x 轴线上时显示所有系列数据
      axisPointer: {
        type: 'line', //提示线，可以改成 shadow 或 cross
      },
    },
    legend: {
      itemWidth: 8, // 设置图例颜色块的宽度
      itemHeight: 8, // 设置图例颜色块的高度
      textStyle: {
        color: '#fff',
      },
      icon: 'circle',
    },
    grid: props.grid,
    xAxis: {
      type: 'category',
      data: _xAxis,
      axisTick: {
        show: false, // 隐藏刻度线
      },
      axisLine: {
        lineStyle: {
          type: 'dashed', // 设置X轴为虚线
        },
      },
      axisLabel: {
        color: '#fff', // x轴标签字体颜色（红色）
        fontSize: 14, // 可选，字体大小
      },
    },
    yAxis: {
      type: 'value',
      // data: _yAxis,
      minInterval: 1,
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: 'rgba(255,255,255,.3)',
        },
      },
      axisLabel: {
        color: '#fff', // x轴标签字体颜色（红色）
        fontSize: 14, // 可选，字体大小
      },
    },
    series: _data,
  };

  const chart = eCharts.init(messureChartRef.value);
  chart.setOption(option);
  addEventListener('resize', function () {
    chart.resize();
  });
};

watch(
  () => props.dataList,
  () => {
    nextTick(() => {
      renderChart();
    });
  },
);
</script>

<style lang="scss" scoped></style>
